package com.dev.weixin.tools.utils.policy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.dev.weixin.tools.models.base.ErrorMsg;
import com.dev.weixin.tools.models.exceptions.ErrorMsgException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 下载策略（自动判定下载类型）
 * @author 飘渺青衣
 * @see
 */
public class DownloadRequestPolicy extends JsonRequestPolicy<File> {

	private String filedir;

	/**
	 * @param url
	 * @param encoding
	 * @param getParameters
	 * @param jsonObject
	 * @param filedir 下载文件路径（不包括文件名）
	 */
	public DownloadRequestPolicy(String url, String encoding,
			Map<String, String> getParameters, Object jsonObject, String filedir) {
		super(url, encoding, getParameters, jsonObject, File.class);
		this.filedir = filedir;
	}

	@Override
	public File response(HttpResponse response, HttpEntity entity,
			ObjectMapper mapper) throws ErrorMsgException {
		FileOutputStream fos = null;
		InputStream is = null;
		try {
			Header contentType = response.getFirstHeader("Content-Type");
			LOG.info(contentType);
			if (contentType.getValue().indexOf("text") > -1) {
				// 如果返回文本 出错了
				String content = EntityUtils.toString(entity);
				LOG.info(content);
				throw new ErrorMsgException(mapper.readValue(content,
						ErrorMsg.class), content);
			}
			Header disposition = response.getFirstHeader("Content-disposition");
			String dispos = disposition.getValue();
			String filename = dispos.substring(22, dispos.length() - 1);
			StringBuilder s = new StringBuilder(filedir);
			if (!filedir.endsWith(File.separator)) {
				s.append(File.separator);
			}
			s.append(filename);
			String filepath = s.toString();
			LOG.info(filepath);
			byte[] buff = new byte[8192];
			int len = 0;
			fos = new FileOutputStream(filepath);
			is = entity.getContent();
			while ((len = is.read(buff)) > 0) {
				fos.write(buff, 0, len);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
			}
			return new File(filepath);
		} catch (FileNotFoundException e) {
			LOG.error(e);
		} catch (IllegalStateException e) {
			LOG.error(e);
		} catch (IOException e) {
			LOG.error(e);
		} finally {
        	if(is != null) {
        		try {
					is.close();
				} catch (IOException e) {}
        	}
        	if(fos != null) {
        		try {
					fos.close();
				} catch (IOException e) {}
        	}
        }
		return null;
	}

	public String getFiledir() {
		return filedir;
	}

}
